import AsyncStorage from "@react-native-community/async-storage";

const FAVORITE_KEY_PREFIX = 'favorite_';

export default class FavoriteAddRemove {
  construct(flag) {
    this.favoriteKey = FAVORITE_KEY_PREFIX + flag
  }

  // 保存收藏
  saveFavoriteItem(key, value) {
    AsyncStorage.setItem(key, value, (error, result) => {
      if (!error) {
        // 更新Favorite的key
        this.updateFavoriteKeys(key, true)
      }
    })
  }

  // 更新收藏的key
  updateFavoriteKeys = (key, isAdd) => {
    AsyncStorage.getItem(this.favoriteKey, (error, result) => {
      if (!error) {
        let favoriteKeys = [];
        if (result) {
          favoriteKeys = JSON.parse(result)
        }
        let index = favoriteKeys.indexOf(key);

        if (isAdd) {
          // 如果是添加且key不存在则添加到数组
          if (index === -1) favoriteKeys.push(key)
        } else {  //  如果是删除且
          if (index !== -1) favoriteKeys.splice(index, 1)
        }
        AsyncStorage.setItem(this.favoriteKey, JSON.stringify(favoriteKeys))
      }
    })
  };

  // 获取收藏的keys
  getFavoriteKeys = () => {
    return new Promise((resolve, reject) => {
      AsyncStorage.getItem(this.favoriteKey, (error, result) => {
        if (!error) {
          try {
            resolve(JSON.parse(result))
          } catch (e) {
            reject(e)
          }
        } else {
          reject(error)
        }
      })
    })
  };

  // 取消收藏，移除已经收藏的项目
  removeFavoriteItem(key) {
    AsyncStorage.removeItem(key, (error, result) => {
      if (!error) {
        this.updateFavoriteKeys(key, false)
      }
    })
  }

  // 获取所有的收藏
  getAllItems = () => {
    return new Promise((resolve, reject) => {
      this.getFavoriteKeys()
        .then(keys => {
          let items = [];
          if (keys) {
            AsyncStorage.multiGet(keys, (err, stores) => {
              try {
                stores.map((result, i) => {
                  let key = result[0];
                  let value = result[1];
                  if (value) items.push(JSON.parse(value))
                });
                resolve(items)
              } catch (err) {
                reject(err)
              }
            })
          } else {
            resolve(items)
          }
        })
        .catch(e => {
          reject(e)
        })
    })
  }
}